package apps.buscoplan;

import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectOutputStream.PutField;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.impl.client.DefaultHttpClient;

import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager;


import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.apps.events.R;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class AccountListView extends ListActivity implements AccountManagerCallback {
	final public String TAG = "AccountListView";
	
	protected AlertDialog alertDialog = null;
	protected Account[] accounts = null;
	GoogleAccountManager googleAccountManager = null;
//	protected ListView listView = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		googleAccountManager = new GoogleAccountManager( this );
    	accounts = googleAccountManager.getAccounts();
		setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, accountArray2StringArray(accounts)));

		getListView().setTextFilterEnabled(true);
	}
	
	@Override
	public void onListItemClick(ListView l, View v, int position, long id)
	{
		super.onListItemClick(l, v, position, id);
		String account = l.getItemAtPosition(position).toString();	
		try
		{
			getAccount (account);
			
			getIntent().putExtra(BuscoplanActivity.SELECTED_ACCOUNT_NAME, account); 
			setResult(RESULT_OK, getIntent()); 
			finish();	
		}
		catch (InvalidObjectException e)
		{
			error ("La aplicación se encuentra en un estado inválido y se cerrará");
		}
		catch (Exception e) {
			Toast.makeText(getApplicationContext(), "La cuenta seleccionada no es válida", Toast.LENGTH_LONG);
		}
	}
	
	private Account getAccount(String account) throws InvalidObjectException {
		if (googleAccountManager != null){
			return googleAccountManager.getAccountByName(account);
		}
		else {
			throw new InvalidObjectException ("La actividad se encuentra en un estado inválido");
		}
	}

	@Override
	public void onBackPressed ()
	{
		showDialogConfirm();
	}
	
	public void showDialogConfirm ()
	{
		if (alertDialog==null)
		{
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Debes seleccionar una cuenta, ¿seguro que quieres salir?")
			       .setCancelable(false)
			       .setPositiveButton("Sí", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			        	   AccountListView.this.error ("Saliendo");		        	   
			           }
			       })
			       .setNegativeButton("No", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			                dialog.cancel();
			           }
			       });
			alertDialog = builder.create();
		}
		
		alertDialog.show();
	}
	
	//if error close actiity
	protected void error( String errMsg ) {
		if (errMsg != null)
		{
			Toast.makeText(getApplicationContext(), errMsg , Toast.LENGTH_LONG);	
		}
		setResult(RESULT_CANCELED);
		finish();		
	}

	public String [] accountArray2StringArray  (Account [] accounts)
	{
		String [] accountsStr = new String [accounts.length];
		for (int i=0; i<accounts.length; i++)
		{
			accountsStr[i]=accounts[i].name;
		}
		return accountsStr;
	}

	@Override
	public void run(AccountManagerFuture result) {
		Bundle bundle;
        try {
                bundle = (Bundle) result.getResult();
                Intent intent = (Intent)bundle.get(AccountManager.KEY_INTENT);
                if(intent != null) {
                    // User input required
                    startActivity(intent);
                } else {
                    DefaultHttpClient http_client = new DefaultHttpClient();
                    http_client.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);

                    String auth_token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
                    HttpGet http_get = new HttpGet("https://yourapp.appspot.com/_ah/login?continue=http://localhost/&auth=" + auth_token);
                    org.apache.http.HttpResponse response;
                    response = http_client.execute( http_get);
                    if(response.getStatusLine().getStatusCode() != 302){
                    	return;
                    }
              
                }
        } catch (Exception e) {
            e.printStackTrace();
            error(e.getMessage());
        }
	}
}